from odoo import models, fields, _, api
from odoo.exceptions import UserError
import logging

logger = logging.getLogger(__name__)


class Person(models.Model):
    _name = 'person.info'
    _description = 'The information of people'

    name = fields.Char(
        '姓名',
        required=True
    )

    gender = fields.Selection([
        ('男', '男'),
        ('女', '女'),
    ], string='性别', defaut='男', index=True)

    school = fields.Selection([
        ('计算机与信息工程学院', '计算机与信息工程学院'),
        ('外国语学院', '外国语学院'),
        ('马克思主义学院', '马克思主义学院'),
        ('数学与统计学学院', '数学与统计学学院'),
        ('体育学院', '体育学院'),
        ('文学院', '文学院'),
        ('艺术学院', '艺术学院'),
        ('新闻传播学院', '新闻传播学院'),
        ('政法与公共管理学院', '政法与公共管理学院'),
        ('资源环境学院', '资源环境学院'),
        ('历史文化学院', '历史文化学院'),
        ('化学化工学院', '化学化工学院'),
        ('物理与电子科学学院', '物理与电子科学学院'),
        ('教育学院', '教育学院'),
        ('哲学院', '哲学院'),
        ('生命科学学院', '生命科学学院'),
        ('材料科学与工程学院', '材料科学与工程学院'),
        ('商学院', '商学院')
    ], string='所在学院', defaut='计算机与信息工程学院', index=True, )

    telephone = fields.Char(
        '联系电话',
    )

    q_q = fields.Char(
        'QQ号',
    )

    ability = fields.Many2one(
        'group.info',
        string='技术组'
    )

    ability_text = fields.Char(
        string='技术组',
        compute='_ability_text',
        store=True
    )

    classroom = fields.Char(
        '专业班级',
    )

    batch = fields.Char(
        '批次',
    )

    grade = fields.Selection([('2016', '2016'),
                              ('2017', '2017'),
                              ('2018', '2018'),
                              ('2019', '2019')], string='年级', defaut='2019', index=True)

    team = fields.One2many(
        'team.info',
        'person_in_charge',
        string='负责项目组'
    )
    team_in = fields.Many2many(
        'team.info',
        string='挂名项目组'
    )

    is_quit = fields.Boolean(
        '是否已退出',
        default=False
    )

    judge_quit = fields.Boolean(
        compute="_compute_is_delete_login_info",
        default=False
    )

    email = fields.Char(
        '邮箱',
        required=True
    )

    is_user = fields.Selection(
        [
            (0, '非用户'),
            (1, '已成为用户'),
        ],
        string='是否成为系统用户', default=0, readonly=True, copy=False, track_visibility='onchange'
    )

    img = fields.Binary(
        string='头像'
    )

    title = fields.Many2one(
        'res.groups',
        domain=[('category_id.name', '=', '湖北大学瑞翼工坊内部管理系统')],
        string='职务'
    )

    new_title = fields.Char(
        default="0"
    )

    title_rule = fields.Char(
        string='职务',
        compute='_change_rule',
        store=True
    )

    # 权限判断
    current_user_is_group_leader = fields.Boolean(
        compute="_compute_current_user"
    )

    current_user_is_deputy_director = fields.Boolean(
        compute="_compute_current_user"
    )

    current_user_is_director = fields.Boolean(
        compute="_compute_current_user"
    )

    current_user_is_teacher = fields.Boolean(
        compute="_compute_current_user"
    )

    current_user_is_group_manager = fields.Boolean(
        compute="_compute_current_user"
    )

    # 判断当前用户是否为自己信息的用户
    current_user = fields.Boolean(
        compute="_compute_current_user"
    )

    # 判断当前用户的身份
    @api.one
    def _compute_current_user(self):
        self.current_user_is_group_leader = self.user_has_groups('sugon_system.asset_group_leader')
        self.current_user_is_deputy_director = self.user_has_groups('sugon_system.asset_deputy_director')
        self.current_user_is_director = self.user_has_groups('sugon_system.asset_director')
        self.current_user_is_teacher = self.user_has_groups('sugon_system.asset_teacher')
        self.current_user_is_group_manager = self.user_has_groups('sugon_system.asset_group_manager')
        # 判断当前用户是否为对应表单的用户
        sql_query = """SELECT login FROM res_users where id = '{id}'""".format(
            id=self.env.uid)
        self.env.cr.execute(sql_query)
        result = self.env.cr.dictfetchall()
        if self.email == result[0].get('login'):
            self.current_user = True

    # 用户退出后，删除用户的登录信息
    def _compute_is_delete_login_info(self):
        if self.is_quit == False:
            pass
        elif self.is_quit == True and self.judge_quit == False:
            sql_delete_user = """DELETE FROM res_users where login = '{email}'""".format(
                email=self.email)
            self.env.cr.execute(sql_delete_user)
            sql_delete_partner = """DELETE FROM res_partner where name = '{name}'""".format(
                name=self.name)
            self.env.cr.execute(sql_delete_partner)
            self.judge_quit == True

    def to_bad_person(self):
        self.ensure_one()
        create_uid = self.env.uid
        # 判断该人员是否已经在当前用户草稿中
        sql_query = """SELECT user_id FROM person_bad where user_id = '{id}' and state = 6 and create_uid = '{create}'""".format(
            id=self.id, create=self.env.uid)
        self.env.cr.execute(sql_query)
        query_result = self.env.cr.dictfetchall()
        if query_result:
            raise UserError(_('%s已经存在于问题人员草稿中!') % self.name)
        # 检验此数据集中是否包含单条数据，否则报错
        sql_query = """SELECT user_id, state FROM person_bad where user_id = '{id}' and state < 6 and state != 1""".format(
            id=self.id)
        self.env.cr.execute(sql_query)
        result = self.env.cr.dictfetchall()
        # state = result[0].get('state')
        # 通过原生sql检验当前人员的id是否在问题人员中有对应的数据
        if result:
            raise UserError(_('%s已经存在于问题人员审核中!') % self.name)
        # 有则报错
        else:
            # logger.info("Here is the name: %s", result)
            check_as_superuser = self.env['person.bad'].sudo()
            # sudo():使用现有数据集创建一个新运行环境，得到一个基于新运行环境的数据集的拷贝
            check_as_superuser.create({
                'user_id': self.id,
            })
            sql_query = """update person_bad set create_uid = '{create_uid}' where user_id = '{user_id}'""".format(
                create_uid=create_uid, user_id=self.id)
            self.env.cr.execute(sql_query)

    def to_person_adjust(self):
        self.ensure_one()
        # 检验此数据集中是否包含单条数据，否则报错
        sql_query = """SELECT name FROM person_adjust where person_adjust.name = '{id}' and person_adjust.state != 2 and person_adjust.state != 1""".format(
            id=self.id)
        self.env.cr.execute(sql_query)
        result = self.env.cr.dictfetchall()
        # 通过原生sql检验当前人员的id是否在调动中有对应的数据，除去已结束的调动
        if result:
            raise UserError(_('%s已经存在与人员调动请求中!') % self.name)
        return {
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form,tree',
            'res_model': 'person.adjust',
            'target': 'new',
            'context': {
                'default_name': self.id,
                'default_gender': self.gender,
                'default_title': self.title,
                'default_school': self.school,
                'default_telephone': self.telephone,
                'default_q_q': self.q_q,
                'default_ability': self.ability,
                'default_classroom': self.classroom,
                'default_batch': self.batch,
                'default_grade': self.grade,
                'default_is_quit': self.is_quit,
                'default_email': self.email,
            }
        }

    def to_user(self):
        new_passd = '$pbkdf2-sha512$25000$S.kdQ0gJAWBsLSWEcM753w$9LTeLUms65K9CWfQEQh1Qr/O5wugp26shOc.W.14bL81vKtEyeCaGxqD14djmhnF8pf/1DmGeZxXiap95eeo3Q'

        self.ensure_one()
        # 检验此数据集中是否包含单条数据，否则报错
        sql_query = """SELECT name FROM res_partner where name = '{name}'""".format(
            name=self.name)
        self.env.cr.execute(sql_query)
        result = self.env.cr.dictfetchall()
        # 通过原生sql检验当前人员是否在用户列表中
        if result:
            pass
            print('hhh')
        # 有则不动
        else:
            check_as_superuser = self.env['res.partner'].sudo()
            # sudo():使用现有数据集创建一个新运行环境，得到一个基于新运行环境的数据集的拷贝
            check_as_superuser.create({
                'name': self.name,
                'email': self.email
            })
            # 查询人员在res_partner中的主键，用于创建用户时关联
            sql_query = """SELECT id FROM res_partner where name = '{name}'""".format(
                name=self.name)
            self.env.cr.execute(sql_query)
            result = self.env.cr.dictfetchall()
            check_as_superuser = self.env['res.users'].sudo()
            check_as_superuser.create({
                'partner_id': result[0]['id'],
                'active': 't',
                'login': self.email
            })
            # 更改初识用户的初始密码为123456
            sql_query = """update res_users set password = '{password}' where login = '{email}'""".format(
                password=new_passd, email=self.email)
            self.env.cr.execute(sql_query)

    @api.onchange('title')
    def _onchange_new_title(self):
        # set auto-changing field
        self.new_title = self.title.id
        sql_query = """UPDATE person_info SET new_title = {new_title} where name = '{name}'""".format(
            new_title=self.new_title, name=self.name)
        self.env.cr.execute(sql_query)

    # 重写write方法
    def write(self, values):
        Person.to_user(self)
        sql_query_user_id = """SELECT * FROM res_users where login = '{email}'""".format(
            email=self.email)
        self.env.cr.execute(sql_query_user_id)
        result_id = self.env.cr.dictfetchall()
        user_id = result_id[0]['id']
        # 查询用户在res.user中的id
        sql_query_user_in_group = """SELECT gid FROM res_groups_users_rel where uid = '{id}'""".format(
            id=user_id)
        self.env.cr.execute(sql_query_user_in_group)
        result_gid = self.env.cr.dictfetchall()
        # 用得到的id查询此用户有哪些权限组
        group_name_list = ['组员', '组长', '技术副总监', '技术总监', '老师', '超级管理员']
        group_id_list = []
        for g_name in group_name_list:
            sql_query_groups = """SELECT * FROM res_groups where name = '{name}'""".format(
                name=g_name)
            self.env.cr.execute(sql_query_groups)
            group_id_list.append(self.env.cr.dictfetchall()[0]['id'])
        # 查询组员、组长等权限组对应的gid
        user_gid_list = []
        for item in result_gid:
            user_gid_list.append(item['gid'])
        # 创建一个列表装有该用户所有的权限组id
        for user_gid in user_gid_list:
            if user_gid in group_id_list:
                # 需要更改的gid
                sql_delete_groups = """DELETE FROM res_groups_users_rel where gid = '{gid}' and uid = '{uid}'""".format(
                    gid=user_gid, uid=user_id)
                self.env.cr.execute(sql_delete_groups)
        # 删除所有跟本系统有关的权限组
        sql_insert_user_group_rel = """INSERT INTO res_groups_users_rel (gid,uid) VALUES ('{gid}','{uid}')""".format(
            gid=self.new_title, uid=user_id)
        self.env.cr.execute(sql_insert_user_group_rel)
        # print(user_gid_list)
        # print(group_id_list)
        return super(Person, self).write(values)

    @api.one
    @api.depends('title')
    def _change_rule(self):
        title_rule = self.env['res.groups'].search(
            [('name', '=', self.title.name)])
        self.title_rule = title_rule.name

    @api.one
    @api.depends('ability')
    def _ability_text(self):
        text = self.env['group.info'].search(
            [('name', '=', self.ability.name)])
        self.ability_text = text.name
